<?php
   if($_POST['submit']!=true) echo '';
   else {
        $image_tempname=$_FILES['img_field']['name'];
		$ImageDir="../site_pict/";
		$ImageThumb=$ImageDir."thumbs/";
		$ImageName=$ImageDir.$image_tempname;
		$to=$_POST['gallery'];
		
	    $sel_u = mysql_query('SELECT teacher_to FROM users WHERE username = "'.$_SESSION['username'].'"');
        $row_u = mysql_fetch_assoc($sel_u);
		
		if($_FILES['img_field']['type']!="image/jpeg" && $_FILES['img_field']['type']!="image/png"){
		      echo "<p class='error'>Файлът трябва да е с разширение JPG или PNG!</p>";
			  die();
		}
		else{
		if(move_uploaded_file($_FILES['img_field']['tmp_name'], $ImageName)){
		   list($width, $height, $type, $attr)=getimagesize($ImageName);
		   
		      $insert=mysql_query('INSERT INTO images(`img`, `to`, `module`) VALUES("'.$image_tempname.'", "'.$to.'", "'.$row_u['teacher_to'].'")');
			  echo "<p class='success'>Успешен запис!</p>";
			  $lastpicid=mysql_insert_id();
			  $newfilename=$ImageDir.$lastpicid.".jpg";
			  
			  if($type==2){
			     rename($ImageName, $newfilename);
			  } elseif($type==3){
			     $image_old=imagecreatefrompng($ImageName);
				 $image_jpg=imagecreatetruecolor($width, $height);
				 imagecopyresampled($image_jpg, $image_old, 0, 0, 0, 0, $width, $height, $width, $height);
				 imagejpeg($image_jpg, $newfilename);
				 imagedestroy($image_old);
				 imagedestroy($image_jpg);
			  }

			   $newthumbname=$ImageThumb.$lastpicid.".jpg";
	  
			   $thumb_width=180;
			   $thumb_height=120;
				  
			   $largeimage=imagecreatefromjpeg($newfilename);
			   $thumb=imagecreatetruecolor($thumb_width, $thumb_height);
			   imagecopyresampled($thumb, $largeimage, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height);
			   imagejpeg($thumb, $newthumbname);
			   imagedestroy($largeimage);
			   imagedestroy($thumb);
		   }
		}
   }
?>